package com.atjg.autocat.utils

import android.content.Context
import android.content.res.AssetFileDescriptor
import android.content.res.Resources
import android.media.MediaPlayer
import android.media.MediaPlayer.OnPreparedListener
import java.io.IOException


class MusicPlayUtils {

    companion object {
        private val mMediaPlayer by lazy {
            MediaPlayer()
        }

        @Throws(
            IllegalStateException::class,
            Resources.NotFoundException::class,
            IOException::class,
            IllegalArgumentException::class
        )
        fun playBgM(mContext: Context, mp3path: Int) {
            try {
                if (mMediaPlayer.isPlaying) {
                    mMediaPlayer.stop()
                }
                this.mMediaPlayer.reset()
                this.mMediaPlayer.setAudioStreamType(3)
                val file: AssetFileDescriptor = mContext.resources.openRawResourceFd(mp3path)
                try {
                    this.mMediaPlayer.setDataSource(
                        file.fileDescriptor,
                        file.startOffset,
                        file.length
                    )
                    this.mMediaPlayer.setOnPreparedListener(
                        OnPreparedListener { mediaPlayer ->
                            mediaPlayer.isLooping = false
                            mediaPlayer.start()
                        })
                    this.mMediaPlayer.prepareAsync()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            } catch (e2: Exception) {
            }
        }
    }


}